import 'dart:io';

import 'package:common_utils/common_utils.dart';
import 'package:emoji_picker_flutter/emoji_picker_flutter.dart';
import 'package:fate_blind_box/chat_view/actions.dart';
import 'package:fate_blind_box/chat_view/chat_input.dart';
import 'package:fate_blind_box/chat_view/chat_message_cell.dart';
import 'package:fate_blind_box/chat_view/chat_net_image.dart';
import 'package:fate_blind_box/chat_view/video_push_widget.dart';
import 'package:fate_blind_box/config/app_style.dart';
import 'package:fate_blind_box/config/app_utils.dart';
import 'package:fate_blind_box/im/person_info.dart';
import 'package:fate_blind_box/im/persondetail.dart';
import 'package:fate_blind_box/routes/page_route_names.dart';
import 'package:fate_blind_box/theme/theme_color.dart';
import 'package:fate_blind_box/utils/provider.dart';
import 'package:fate_blind_box/widget/appbar.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart' as foundation;
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:im_flutter_sdk/im_flutter_sdk.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import 'logic.dart';

class ChatPage extends GetView<ChatLogic> {
  const ChatPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: HzAppBar(
        title: getNavHeader(),
        centerTitle: false,
        backgroundColor: ThemeColor.color19CF8F23,
        actions: [
          getStoreView(),
          getMoreView(),
        ],
      ),
      body: Obx(() {
        if (controller.state.model.value == null) {
          return Container();
        }
        return Column(
          children: <Widget>[
            Container(
              color: ThemeColor.colorD88E4B,
              height: 1.w,
              width: double.infinity,
            ),
            Expanded(
                child: SmartRefresher(
              controller: controller.state.refreshController,
              onRefresh: controller.onRefresh,
              onLoading: controller.onLoading,
              enablePullUp: controller.state.hasMore.value,
              enablePullDown: false,
              child: Container(
                color: ThemeColor.color19CF8F23,
                child: ListView.builder(
                  controller: controller.state.controller,
                  padding: EdgeInsets.only(bottom: 44.w),
                  reverse: true,
                  itemBuilder: (_, index) {
                    if (controller.state.messageList.isNotEmpty == true) {
                      return Obx(() {
                        return ChatMessageCell(
                          message: controller.state.messageList[index],
                          userInfo: controller.state.userInfoList[index],
                        );
                      });
                    } else {
                      return Container();
                    }
                  },
                  itemCount: controller.state.messageList.length,
                ),
              ),
            )),
            SafeArea(
                child: ChatInput(
              conversationId: controller.state.conversationId,
              type: ChatType.Chat,
              moreAction: customMenu(),
            )),
          ],
        );
      }),
    );
  }

  /// 导航栏上面的头像个昵称
  Widget getNavHeader() {
    return Row(
      children: [
        ClipRRect(
          borderRadius: BorderRadius.circular(5),
          child: Image.network(
            controller.state.avatarUrl.value,
            width: 30,
            height: 30,
            fit: BoxFit.cover,
          ),
        ),
        const SizedBox(
          width: 10,
        ),
        Expanded(
          child: Text(
            controller.state.nickName.value,
            style: const TextStyle(
              color: Color(0xff0F1724),
              fontSize: 18,
              fontWeight: FontWeight.w500,
              overflow: TextOverflow.ellipsis,
            ),
          ),
        )
      ],
    );
  }

  Widget getHeader() {
    return Container(
      height: 62,
      margin: const EdgeInsets.fromLTRB(19, 0, 20, 20),
      padding: const EdgeInsets.symmetric(horizontal: 12),
      decoration: BoxDecoration(
          color: Colors.white, borderRadius: BorderRadius.circular(5)),
      child: Row(
        children: [
          GestureDetector(
            onTap: () {
              if (ObjectUtil.isEmpty(controller.state.model.value?.id)) {
                return;
              }
              Get.to(
                  PersonInfo(sig: controller.state.model.value?.id.toString()),
                  routeName: PageRouteNames.personInfoPage);
            },
            child: ClipRRect(
              borderRadius: BorderRadius.circular(3),
              child: ChatNetImage(
                imageUrl: Provider.fixAvatar(
                    controller.state.model.value?.profilePhoto),
                width: 30.w,
                height: 30.w,
                fit: BoxFit.fill,
              ),
            ),
          ),
          const SizedBox(
            width: 10,
          ),
          getCornerView(
              leftTitle: '年龄',
              rightTitle: '${controller.state.model.value?.age}'),
          const SizedBox(
            width: 7,
          ),
          getCornerView(
              leftTitle: '性别',
              rightTitle:
                  controller.state.model.value?.realSex == 2 ? '女' : '男'),
          SizedBox(
            width: 36.w,
          ),
          getStoreView()
        ],
      ),
    );
  }

  Widget getCornerView({String leftTitle = '', String rightTitle = ''}) {
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 3, horizontal: 8),
      decoration: BoxDecoration(
          color: ThemeColor.grayF2F4F5Color,
          borderRadius: BorderRadius.circular(12)),
      child: Text(
        leftTitle + '：' + rightTitle,
        style: TextStyle(color: ThemeColor.textColor3, fontSize: 10),
      ),
    );
  }

  /// 查看更多按钮
  Widget getMoreView() {
    return GestureDetector(
      onTap: () {
        if (ObjectUtil.isEmpty(controller.state.model.value)) {
          return;
        }
        Get.to(PersonDatail(userInfo: controller.state.model.value?.toJson()),
            routeName: PageRouteNames.personDetailPage);
      },
      child: Container(
        padding: const EdgeInsets.only(left: 4, right: 12),
        child: const Icon(
          Icons.more_horiz,
          size: 22,
          color: Colors.black,
        ),
      ),
    );
  }

  /// 店铺按钮
  Widget getStoreView() {
    return Align(
      alignment: Alignment.center,
      child: InkWell(
        onTap: () => Get.toNamed(PageRouteNames.store),
        child: Container(
          width: 46.w,
          height: 24.w,
          decoration: BoxDecoration(
              color: ThemeColor.colorCF8F23,
              borderRadius: BorderRadius.circular(2)),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Image.asset(
                'images/chat/store.png',
                width: 16.w,
                height: 15.w,
                color: Colors.white,
              ),
              SizedBox(width: 4.w),
              Text(
                '店铺',
                style: TextStyle(fontSize: 8.sp),
              )
            ],
          ),
        ),
      ),
    );
  }

  // 表情键盘
  Widget emojiView() {
    return Offstage(
      offstage: !controller.state.emojiShowing.value,
      child: SizedBox(
          height: 250.w,
          child: EmojiPicker(
            textEditingController: controller.state.messController,
            onBackspacePressed: controller.onBackspacePressed,
            onEmojiSelected: (value, e) {
              controller.state.canSend.value = true;
              controller.state.emojiList.add(e.emoji);
              controller.state.centext = controller.state.emojiList.join('');
            },
            config: Config(
              columns: 7,
              emojiSizeMax: 32 *
                  (foundation.defaultTargetPlatform == TargetPlatform.iOS
                      ? 1.30
                      : 1.0),
              verticalSpacing: 0,
              horizontalSpacing: 0,
              gridPadding: EdgeInsets.zero,
              // initCategory: Category.RECENT,
              bgColor: const Color(0xFFF2F2F2),
              indicatorColor: ThemeColor.appColor,
              iconColor: Colors.grey,
              iconColorSelected: ThemeColor.appColor,
              backspaceColor: ThemeColor.appColor,
              skinToneDialogBgColor: Colors.white,
              skinToneIndicatorColor: Colors.grey,
              enableSkinTones: true,
              recentTabBehavior: RecentTabBehavior.RECENT,
              recentsLimit: 28,
              replaceEmojiOnLimitExceed: false,
              noRecents: const Text(
                'No Recents',
                style: TextStyle(fontSize: 20, color: Colors.black26),
                textAlign: TextAlign.center,
              ),
              loadingIndicator: const SizedBox.shrink(),
              tabIndicatorAnimDuration: kTabScrollDuration,
              categoryIcons: const CategoryIcons(),
              buttonMode: ButtonMode.MATERIAL,
              checkPlatformCompatibility: true,
            ),
          )),
    );
  }

  // 自定义按钮
  // 自定义按钮
  List<ActionItem> customMenu() {
    return [
      ActionItem(
        type: 'custom',
        icon: Image.asset(
          'images/chat/chat_photo.png',
          width: 48.w,
          height: 48.w,
          fit: BoxFit.fill,
        ),
        title: "相册",
        onTap: _checkPermissions,
      ),
      ActionItem(
        type: 'custom',
        icon: Image.asset(
          'images/chat/chat_camera.png',
          width: 48.w,
          height: 48.w,
          fit: BoxFit.fill,
        ),
        title: "相机",
        onTap: _checkCameraPermissions,
      ),
      ActionItem(
        type: 'custom',
        icon: Image.asset(
          'images/chat/transfer.png',
          width: 48.w,
          height: 48.w,
          fit: BoxFit.fill,
        ),
        title: "转账",
        onTap: transferAction,
      ),
      // ActionItem(
      //   type: 'custom',
      //   icon: Image.asset(
      //     'assets/images/chat/chat_audio.png',
      //     fit: BoxFit.cover,
      //     // color: Colors.red,
      //   ),
      //   title: "语音通话",
      //   onTap: controller.audioCallAction,
      // ),
      // ActionItem(
      //   type: 'custom',
      //   icon: Image.asset(
      //     'assets/images/chat/chat_video.png',
      //     width: 48.w,
      //     height: 48.w,
      //     fit: BoxFit.fill,
      //   ),
      //   title: "视频通话",
      //   onTap: controller.videoCallAction,
      // ),
    ];
  }

  /// 检查相册权限
  _checkPermissions(BuildContext context) async {
    bool isGranted = await AppUtils.permissionPhotos();
    if (isGranted) {
      _onPhotoActionTap(context);
    } else {
      permissionTips(context);
    }
  }

  /// 权限申请
  permissionTips(BuildContext context) async {
    if (Platform.isAndroid) {
      var status = await permissionDialog(
        Get.context!,
        title: "“都肆商圈”需要使用您的相册权限，是否允许？",
        content: '不允许您将无法发送照片以及视频',
      );
      if (status == '不允许') {
        return;
      }
    }
    requestPermission(context);
  }

  ///申请权限
  void requestPermission(BuildContext context) async {
    var permission = await AppUtils.getPhotoPermission();
    PermissionStatus status = await permission.request();
    if (status.isGranted) {
      _onPhotoActionTap(Get.context!);
    }
  }

  /// 弹窗选择视频或者图片
  _onPhotoActionTap(BuildContext context) {
    var style = TextStyle(fontSize: 16, color: '#333333'.stringToColor);
    showBottomChoose<String>(
            context: context,
            actions: [
              CupertinoActionSheetAction(
                onPressed: () {
                  Navigator.pop(context, '图片');
                },
                child: Text(
                  '图片',
                  style: style,
                ),
              ),
              CupertinoActionSheetAction(
                onPressed: () {
                  Navigator.pop(context, '视频');
                },
                child: Text(
                  '视频',
                  style: style,
                ),
              ),
            ],
            showCancel: true)
        .then((value) async {
      if (value != null) controller.selectPhoto(value);
    });
  }

  /// 检查相机权限
  void _checkCameraPermissions(BuildContext context) async {
    final permissions = <Permission>[
      Permission.camera,
      Permission.microphone,
    ];
    if (Platform.isAndroid) {
      permissions.add(await AppUtils.getPhotoPermission());
    }
    List<Permission> missed = [];
    for (var permission in permissions) {
      PermissionStatus status = await permission.status;
      if (status != PermissionStatus.granted) {
        missed.add(permission);
      }
    }
    if (missed.isNotEmpty) {
      permissionCameraTips(context, missed);
    } else {
      controller.cameraAction(context);
    }
  }

  /// 相机权限本地弹窗
  permissionCameraTips(BuildContext context, List<Permission> missed) async {
    if (Platform.isAndroid && missed.isNotEmpty) {
      var status = await permissionDialog(
        Get.context!,
        title: "“都肆商圈”需要使用您的相机、麦克风、照片存储权限，是否允许？",
        content: '不允许您将无法拍摄照片以及视频',
      );
      if (status == '不允许') {
        return;
      }
    }
    requestPermission2(context, missed);
  }

  /// 申请相机或者麦克风权限
  requestPermission2(BuildContext context, List<Permission> missed) async {
    List<Permission> showRationale = [];
    await Permission.camera.request();
    for (Permission permission in missed) {
      PermissionStatus status = await permission.request();
      if (status != PermissionStatus.granted) {
        showRationale.add(permission);
      }
    }
    if (showRationale.isEmpty) {
      controller.cameraAction(context);
    } else {
      if (Platform.isAndroid) openAppSettings;
    }
  }

  /// 转账
  void transferAction(BuildContext context) {
    Get.toNamed(PageRouteNames.accounts, arguments: {
      'avatarUrl': controller.state.avatarUrl.value,
      'nickName': controller.state.nickName.value,
    });
  }

  Future<T?> showBottomChoose<T>(
      {required BuildContext context,
      required List<CupertinoActionSheetAction> actions,
      Widget? title,
      Widget? message,
      bool showCancel = true}) async {
    return showCupertinoModalPopup<T>(
        context: context,
        barrierColor: const Color(0x66000000),
        builder: (BuildContext context) {
          return CupertinoActionSheet(
            title: title,
            message: message,
            cancelButton: showCancel
                ? CupertinoActionSheetAction(
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                    child: Text(
                      "取消",
                      style: TextStyle(
                          fontSize: 16, color: '#333333'.stringToColor),
                    ),
                  )
                : null,
            actions: actions
                .map((e) => Container(
                      color: Colors.white,
                      child: e,
                    ))
                .toList(),
          );
        });
  }
}
